# -*- coding: utf-8 -*-
# @Time    : 2020/3/17 上午10:33
# @Author  : lilong

import re
from abc import ABCMeta, abstractmethod

"""
# 过滤器框架2
（1）定义过滤器抽象类，定义抽象方法
（2）定义子类，继承抽象类，实现抽象方法
"""


# 先定义框架，有了框架，下面才基于框架具体实现
class Filter(metaclass=ABCMeta):
    """过滤器"""

    @abstractmethod
    def doFilter(self, elements):
        """过滤方法"""
        pass


class FilterChain(Filter):
    """过滤器链
    （1）继承过滤器抽象类
    （2）添加的具体过滤器子类也必须是继承自抽象类
    """

    def __init__(self):
        self._filters = []

    def addFilter(self, filter):
        self._filters.append(filter)

    def removeFilter(self, filter):
        self._filters.remove(filter)

    def doFilter(self, elements):
        for filter in self._filters:
            elements = filter.doFilter(elements)
        return elements


"""
# 有了上面的框架，基于框架的实现
"""


class SensitiveFilter(Filter):
    """敏感词过滤"""

    def __init__(self):
        self.__sensitives = ["黄色", "台独", "贪污"]

    def doFilter(self, elements):

        # 敏感词列表转换成正则表达式
        regex = ""
        for word in self.__sensitives:
            regex += word + "|"
        regex = regex[0: len(regex) - 1]

        # 对每个元素进行过滤
        newElements = []
        for element in elements:
            item, num = re.subn(regex, "", element)
            newElements.append(item)

        return newElements


class HtmlFilter(Filter):
    """HTML特殊字符转换"""

    def __init__(self):
        self.__wordMap = {
            "&": "&amp;",
            "'": " &apos;",
            ">": "&gt;",
            "<": "&lt;",
            "\"": " &quot;",
        }

    def doFilter(self, elements):
        newElements = []
        for element in elements:
            for key, value in self.__wordMap.items():
                element = element.replace(key, value)
            newElements.append(element)
        return newElements


def Filtercontent():
    contents = [
        '有人出售黄色书：<黄情味道>',
        '有人企图搞台独活动, ——"造谣咨询"',
    ]

    print("过滤前的内容：", contents)
    filterChain = FilterChain()  # 定义过滤器列表
    filterChain.addFilter(SensitiveFilter())  # 添加过滤器1
    filterChain.addFilter(HtmlFilter())  # 添加过滤器2
    newContents = filterChain.doFilter(contents)
    print("过滤后的内容：", newContents)


if __name__ == '__main__':
    Filtercontent()
